package utils;


import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {

    private static DataSource dataSource;
    private static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    static {

        try {
            Properties properties = new Properties();
//            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druidJDBC.properties");
            InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("druidJDBC.properties");

//            ClassLoader classLoader = JdbcUtils.class.getClassLoader();
//            System.out.println("******\r\n" + classLoader.getParent().getParent() + "\r\n**********");
//            InputStream is = classLoader.getResourceAsStream("druidJDBC.properties");

            properties.load(is);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将从连接池中获取到的连接存放在ThreadLocal对象中，使得此后同一个线程调用同一个Connection对象，实现事务管理
     */
    public static Connection getConnection() {

        Connection conn = connectionThreadLocal.get();

        if (conn == null) {
            try {
                conn = dataSource.getConnection();
                connectionThreadLocal.set(conn);      //保存ThreadLocal对象中
                conn.setAutoCommit(false);            //手动管理事务
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return conn;
    }

    /**
     * 提交事务，并关闭连接
     */
    public static void commitAndClose() {
        DbUtils.commitAndCloseQuietly(connectionThreadLocal.get());

        //Tomcat使用了线程池技术，所以需要remove
        connectionThreadLocal.remove();
    }

    /**
     * 回滚数据，并关闭连接
     */
    public static void rollbackAndClose() {
        DbUtils.rollbackAndCloseQuietly(connectionThreadLocal.get());
        //Tomcat使用了线程池技术，所以需要remove
        connectionThreadLocal.remove();
    }

//    @Deprecated
//    public static void closeResource(Connection conn) {
//        DbUtils.closeQuietly(conn);
//
//    }
}
